package com.maodou.android.data.remote

import android.content.Context
import android.os.Build
import com.maodou.core.manager.GlobalStateManager
import dagger.hilt.android.qualifiers.ApplicationContext
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 动态请求头提供器
 * 负责提供 token、语言、设备信息等动态请求头
 */
@Singleton
class DynamicHeaderProvider @Inject constructor(
    @ApplicationContext private val context: Context,
    private val globalStateManager: GlobalStateManager
) {
    
    /**
     * 获取动态请求头
     */
    fun getHeaders(): Map<String, String> {
        val headers = mutableMapOf<String, String>()
        
        // 基础请求头
        headers["User-Agent"] = "MaoDouTools/1.0"
        headers["Accept"] = "application/json"
        headers["Content-Type"] = "application/json"
        
        // Token（如果已登录）
        globalStateManager.loginToken.value?.let { token ->
            if (token.isNotBlank()) {
                headers["Authorization"] = "Bearer $token"
            }
        }
        
        // 语言设置
        val language = getLanguage()
        headers["Accept-Language"] = language
        headers["X-App-Language"] = language
        
        // 设备信息
        headers["X-Device-Platform"] = "Android"
        headers["X-Device-OS-Version"] = Build.VERSION.RELEASE
        headers["X-Device-API-Level"] = Build.VERSION.SDK_INT.toString()
        headers["X-Device-Model"] = "${Build.MANUFACTURER} ${Build.MODEL}"
        headers["X-App-Version"] = getAppVersion()
        
        // 用户ID（如果已登录）
        globalStateManager.getCurrentUserId()?.let { userId ->
            headers["X-User-ID"] = userId
        }
        
        return headers
    }
    
    /**
     * 获取当前语言设置
     */
    private fun getLanguage(): String {
        // 优先从应用配置获取
        val configLanguage = globalStateManager.getStringConfig("app_language", "")
        if (configLanguage.isNotBlank()) {
            return configLanguage
        }
        
        // 使用系统语言
        val locale = Locale.getDefault()
        return "${locale.language}-${locale.country}"
    }
    
    /**
     * 获取应用版本
     */
    private fun getAppVersion(): String {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            packageInfo.versionName ?: "1.0.0"
        } catch (e: Exception) {
            "1.0.0"
        }
    }
}